﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ArtMath
{
    public class clsNormal : clsFormulaBase
    {
        string text;
        float emSize = 20;
        public List<clsForchar> chars = new List<clsForchar>();
        public clsNormal(PictureBox pb, string txt) : base(pb)
        {
            Text = txt;
        }
        public string Text
        {
            get { return text; }
            set
            {
                text = value;
                char[] cs = text.ToCharArray();
                chars.Clear();
                for (int i = 0; i < cs.Length; i++)
                {
                    chars.Add(new clsForchar(picturebox, this, cs[i], Color.Black, i));
                }
                foreach (Parameter item in Program.WinDocuments.SelectedDocument.Parameters)
                {
                    searchItalic(item.Name);
                }
                searchItalic("π");
                searchItalic("e");
                double width = 0;
                foreach (clsForchar item in chars)
                {
                    item.Size = SizeD.FromSize(TextRenderer.MeasureText(item.Char.ToString(), new Font("Times New Roman", emSize, item.Italic ? FontStyle.Italic : FontStyle.Regular)));
                    width += item.Size.Width;
                }
                Size = new SizeD(width + 8, chars[0].Size.Height);
                picturebox.Invalidate();
            }
        }
        void searchItalic(string pat)
        {
            MatchCollection mc = Regex.Matches(text, "\\b" + pat + "\\b");
            foreach (Match match in mc)
            {
                for (int i = match.Index; i < pat.Length + match.Index; i++)
                {
                    chars[i].Italic = true;
                }
            }
        }
        public override void Paint(Graphics gra)
        {
            double left = 0;
            foreach (clsForchar item in chars)
            {
                gra.DrawString(item.Char.ToString(), new Font("Times New Roman", emSize, item.Italic ? FontStyle.Italic : FontStyle.Regular), new SolidBrush(item.Color), new PointF((float)(Location.X + left), (float)(Location.Y - item.Yoffset)));
                left += item.Size.Width;
            }
            base.Paint(gra);
        }
        public override string ToString()
        {
            return text;
        }
    }
}
